#include "hintlineedit.h"
#include "common/tdebug.h"

#define HINT_STYLE "color:rgb(230, 230, 230);background-color: rgb(255, 255, 255);"
#define TEXT_STYLE "color:rgb(0, 0, 0);background-color: rgb(255, 255, 255);"
HintLineEdit::HintLineEdit(QString hintText,QWidget *parent) :
    QLineEdit(hintText,parent)
{
    mHintText = hintText;
    init();

}

HintLineEdit::HintLineEdit(QWidget *parent) :
    QLineEdit(parent)
{
    mHintText = "";
    init();

}

void HintLineEdit::setHintText(QString text)
{
    mHintText = text;

}

void HintLineEdit::setText(const QString &text)
{
    if(text==mHintText)
    {
        QLineEdit::setEchoMode(Normal);
    }
    else
    {
        QLineEdit::setEchoMode(mEchoMode);
    }
    QLineEdit::setText(text);
}

void HintLineEdit::init()
{
    this->setCursorPosition(0);
    this->setText(mHintText);
    connect(this,SIGNAL(textEdited(QString)),this,SLOT(hintTextEdited(QString)));
    //connect(this,SIGNAL(textChanged(QString)),this,SLOT(hintTextEdited(QString)));
    this->setStyleSheet(HINT_STYLE);

}

void HintLineEdit::setEchoMode(EchoMode mode)
{
    mEchoMode = mode;
    if(this->text()==mHintText)
    {
        setHintStatus();
    }
    else
    {
       // QLineEdit::setEchoMode(mEchoMode);
        setNormalStatus();
    }
}

void HintLineEdit::setHintStatus()
{
    this->setStyleSheet(HINT_STYLE);
    this->setCursorPosition(0);
    QLineEdit::setEchoMode(Normal);
}

void HintLineEdit::setNormalStatus()
{
    this->setStyleSheet(TEXT_STYLE);
    QLineEdit::setEchoMode(mEchoMode);
}



void HintLineEdit::enterEvent(QEvent *e)
{

    if(this->text()==mHintText)
    {
        this->setText("");
        this->setCursorPosition(0);
        setNormalStatus();

    }
    else
        QLineEdit::enterEvent(e);

}

void HintLineEdit::hintTextEdited(const QString &str)
{
    int len = str.length();
    if(len==0)
    {
        this->setText(mHintText);
        setHintStatus();
    }
    else if(len == mHintText.length()+1)
    {
        QString s = str.right(len-1);
        if(s==mHintText)
        {

            setText(str.at(0));
            setNormalStatus();
        }
    }
    else if(str== mHintText)
    {
        setCursorPosition(0);
        setHintStatus();
    }
    else if(len==1)
    {
        setNormalStatus();
    }

}
